home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 4 / Apprentice-Release4.iso / Source Code / Libraries / Apache 1.0 / src / mod_cgi.c < prev    next >
Text File  |  1995-12-04  |  12KB  |  360 lines

  1.  
  2. /* ====================================================================
  3.  * Copyright (c) 1995 The Apache Group.  All rights reserved.
  4.  *
  5.  * Redistribution and use in source and binary forms, with or without
  6.  * modification, are permitted provided that the following conditions
  7.  * are met:
  8.  *
  9.  * 1. Redistributions of source code must retain the above copyright
  10.  *    notice, this list of conditions and the following disclaimer. 
  11.  *
  12.  * 2. Redistributions in binary form must reproduce the above copyright
  13.  *    notice, this list of conditions and the following disclaimer in
  14.  *    the documentation and/or other materials provided with the
  15.  *    distribution.
  16.  *
  17.  * 3. All advertising materials mentioning features or use of this
  18.  *    software must display the following acknowledgment:
  19.  *    "This product includes software developed by the Apache Group
  20.  *    for use in the Apache HTTP server project (http://www.apache.org/)."
  21.  *
  22.  * 4. The names "Apache Server" and "Apache Group" must not be used to
  23.  *    endorse or promote products derived from this software without
  24.  *    prior written permission.
  25.  *
  26.  * 5. Redistributions of any form whatsoever must retain the following
  27.  *    acknowledgment:
  28.  *    "This product includes software developed by the Apache Group
  29.  *    for use in the Apache HTTP server project (http://www.apache.org/)."
  30.  *
  31.  * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
  32.  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  33.  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  34.  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE APACHE GROUP OR
  35.  * IT'S CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36.  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37.  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38.  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  39.  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40.  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41.  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  42.  * OF THE POSSIBILITY OF SUCH DAMAGE.
  43.  * ====================================================================
  44.  *
  45.  * This software consists of voluntary contributions made by many
  46.  * individuals on behalf of the Apache Group and was originally based
  47.  * on public domain software written at the National Center for
  48.  * Supercomputing Applications, University of Illinois, Urbana-Champaign.
  49.  * For more information on the Apache Group and the Apache HTTP server
  50.  * project, please see <http://www.apache.org/>.
  51.  *
  52.  */
  53.  
  54.  
  55. /*
  56.  * http_script: keeps all script-related ramblings together.
  57.  * 
  58.  * Compliant to CGI/1.1 spec
  59.  * 
  60.  * Adapted by rst from original NCSA code by Rob McCool
  61.  *
  62.  * Apache adds some new env vars; REDIRECT_URL and REDIRECT_QUERY_STRING for
  63.  * custom error responses, and DOCUMENT_ROOT because we found it useful.
  64.  * It also adds SERVER_ADMIN - useful for scripts to know who to mail when 
  65.  * they fail.
  66.  */
  67.  
  68. #include "httpd.h"
  69. #include "http_config.h"
  70. #include "http_request.h"
  71. #include "http_core.h"
  72. #include "http_protocol.h"
  73. #include "http_main.h"
  74. #include "http_log.h"
  75. #include "util_script.h"
  76.  
  77. /* KLUDGE --- for back-combatibility, we don't have to check ExecCGI
  78.  * in ScriptAliased directories, which means we need to know if this
  79.  * request came through ScriptAlias or not... so the Alias module
  80.  * leaves a note for us.
  81.  */
  82.  
  83. int is_scriptaliased (request_rec *r)
  84. {
  85.     char *t = table_get (r->notes, "alias-forced-type");
  86.     return t && (!strcmp (t, CGI_MAGIC_TYPE));
  87. }
  88.  
  89. /****************************************************************
  90.  *
  91.  * Actual CGI handling...
  92.  */
  93.  
  94. void add_cgi_vars(request_rec *r)
  95. {
  96.     table *e = r->subprocess_env;
  97.  
  98.     table_set (e, "GATEWAY_INTERFACE","CGI/1.1");
  99.     table_set (e, "SERVER_PROTOCOL", r->protocol);
  100.     table_set (e, "REQUEST_METHOD", r->method);
  101.     table_set (e, "QUERY_STRING", r->args ? r->args : "");
  102.     
  103.     /* Note that the code below special-cases scripts run from includes,
  104.      * because it "knows" that the sub_request has been hacked to have the
  105.      * args and path_info of the original request, and not any that may have
  106.      * come with the script URI in the include command.  Ugh.
  107.      */
  108.     
  109.     if (!r->path_info || !*r->path_info || !strcmp (r->protocol, "INCLUDED")) {
  110.         table_set (e, "SCRIPT_NAME", r->uri);
  111.     } else {
  112.         int path_info_start = strlen (r->uri) - strlen (r->path_info);
  113.     
  114.     r->uri[path_info_start] = '\0';
  115.     table_set (e, "SCRIPT_NAME", r->uri);
  116.     r->uri[path_info_start] = '/';
  117.     }
  118.     
  119.     if (r->path_info && r->path_info[0]) {
  120.     /*
  121.       * To get PATH_TRANSLATED, treat PATH_INFO as a URI path.
  122.      * Need to re-escape it for this, since the entire URI was
  123.      * un-escaped before we determined where the PATH_INFO began.
  124.       */
  125.     request_rec *pa_req = sub_req_lookup_uri(
  126.                     escape_uri(r->pool, r->path_info), r);
  127.       
  128.         table_set (e, "PATH_INFO", r->path_info);
  129.  
  130.     /* Don't bother destroying pa_req --- it's only created in
  131.      * child processes which are about to jettison their address
  132.      * space anyway.  BTW, we concatenate filename and path_info
  133.      * from the sub_request to be compatible in case the PATH_INFO
  134.      * is pointing to an object which doesn't exist.
  135.      */
  136.     
  137.     if (pa_req->filename)
  138.         table_set (e, "PATH_TRANSLATED",
  139.                pstrcat (r->pool, pa_req->filename, pa_req->path_info,
  140.                 NULL));
  141.     }
  142. }
  143.  
  144. struct cgi_child_stuff {
  145.     request_rec *r;
  146.     int nph;
  147.     char *argv0;
  148. };
  149.  
  150. void cgi_child (void *child_stuff)
  151. {
  152.     struct cgi_child_stuff *cld = (struct cgi_child_stuff *)child_stuff;
  153.     request_rec *r = cld->r;
  154.     char *argv0 = cld->argv0;
  155.     int nph = cld->nph;
  156.  
  157. #ifdef DEBUG_CGI    
  158.     FILE *dbg = fopen ("/dev/tty", "w");
  159.     int i;
  160. #endif
  161.     
  162.     char **env;
  163.     char err_string[HUGE_STRING_LEN];
  164.     
  165. #ifdef DEBUG_CGI    
  166.     fprintf (dbg, "Attempting to exec %s as %sCGI child (argv0 = %s)\n",
  167.         r->filename, nph ? "NPH " : "", argv0);
  168. #endif    
  169.  
  170.     add_cgi_vars (r);
  171.     env = create_environment (r->pool, r->subprocess_env);
  172.     
  173. #ifdef DEBUG_CGI    
  174.     fprintf (dbg, "Environment: \n");
  175.     for (i = 0; env[i]; ++i) fprintf (dbg, "'%s'\n", env[i]);
  176. #endif
  177.     
  178.     chdir_file (r->filename);
  179.     error_log2stderr (r->server);
  180.     if (nph) client_to_stdout (r->connection);
  181.     
  182.     /* Transumute outselves into the script.
  183.      * NB only ISINDEX scripts get decoded arguments.
  184.      */
  185.     
  186.     cleanup_for_exec();
  187.     
  188.     if((!r->args) || (!r->args[0]) || (ind(r->args,'=') >= 0)) 
  189.         execle(r->filename, argv0, NULL, env);
  190.     else 
  191.         execve(r->filename, create_argv(r->pool, argv0, r->args), env);
  192.  
  193.     /* Uh oh.  Still here.  Where's the kaboom?  There was supposed to be an
  194.      * EARTH-shattering kaboom!
  195.      *
  196.      * Oh, well.  Muddle through as best we can...
  197.      *
  198.      * (NB we can't use log_error, or anything like that, because we
  199.      * just closed the file descriptor which r->server->error_log
  200.      * was tied to in cleanup_for_exec().  It's only available on stderr
  201.      * now, so that's what we use).
  202.      */
  203.     
  204.     sprintf(err_string,
  205.         "exec of %s failed, errno is %d\n", r->filename, errno);
  206.     write(2, err_string, strlen(err_string));
  207.     exit(0);
  208. }
  209.  
  210. int cgi_handler (request_rec *r)
  211. {
  212.     int nph;
  213.     char *argv0;
  214.     FILE *script_out, *script_in;
  215.     char argsbuffer[HUGE_STRING_LEN];
  216.     int is_included = !strcmp (r->protocol, "INCLUDED");
  217.     char *lenp = table_get (r->headers_in, "Content-length");
  218.  
  219.     struct cgi_child_stuff cld;
  220.  
  221.     if((argv0 = strrchr(r->filename,'/')) != NULL)
  222.         argv0++;
  223.     else argv0 = r->filename;
  224.  
  225.     nph = !(strncmp(argv0,"nph-",4));
  226.     
  227.     if (!(allow_options (r) & OPT_EXECCGI) && !is_scriptaliased (r)) {
  228.         log_reason("Options ExecCGI is off in this directory", r->filename, r);
  229.     return FORBIDDEN;
  230.     }
  231.     if (nph && is_included) {
  232.         log_reason("attempt to include NPH CGI script", r->filename, r);
  233.     return FORBIDDEN;
  234.     }
  235.     
  236.     if (S_ISDIR(r->finfo.st_mode)) {
  237.         log_reason("attempt to invoke directory as script", r->filename, r);
  238.     return FORBIDDEN;
  239.     }
  240.     if (r->finfo.st_mode == 0) {
  241.         log_reason("script not found or unable to stat", r->filename, r);
  242.     return NOT_FOUND;
  243.     }
  244.     if(!can_exec(&r->finfo)) {
  245.         log_reason("file permissions deny server execution", r->filename, r);
  246.         return FORBIDDEN;
  247.     }
  248.     if ((r->method_number == M_POST || r->method_number == M_PUT)
  249.     && !lenp) {
  250.         log_reason("POST or PUT without Content-length:", r->filename, r);
  251.     return BAD_REQUEST;
  252.     }
  253.  
  254.     add_common_vars (r);
  255.     cld.argv0 = argv0; cld.r = r; cld.nph = nph;
  256.     
  257.     if (!spawn_child (r->connection->pool, cgi_child, (void *)&cld,
  258.               nph ? just_wait : kill_after_timeout,
  259.               &script_out, nph ? NULL : &script_in)) {
  260.         log_reason ("couldn't spawn child process", r->filename, r);
  261.         return SERVER_ERROR;
  262.     }
  263.  
  264.     /* Transfer any put/post args, CERN style...
  265.      * Note that if a buggy script fails to read everything we throw
  266.      * at it, or a buggy client sends too much, we get a SIGPIPE, so
  267.      * we have to ignore SIGPIPE while doing this.  CERN does the same
  268.      * (and in fact, they pretty nearly guarantee themselves a SIGPIPE
  269.      * on every invocation by chasing the real client data with a
  270.      * spurious newline).
  271.      */
  272.     
  273.     if (r->method_number == M_POST || r->method_number == M_PUT) {
  274.         void (*handler)();
  275.     int remaining = atoi (lenp);
  276.     
  277.         hard_timeout ("copy script args", r);
  278.         handler = signal (SIGPIPE, SIG_IGN);
  279.     
  280.     while ((remaining > 0))
  281.     {
  282.         int len_read, len_to_read = remaining;
  283.  
  284.         if (len_to_read > HUGE_STRING_LEN) len_to_read = HUGE_STRING_LEN;
  285.         
  286.         len_read = read_client_block (r, argsbuffer, len_to_read);
  287.         fwrite (argsbuffer, 1, len_read, script_out);
  288.         remaining -= len_read;
  289.     }
  290.     
  291.     fflush (script_out);
  292.     signal (SIGPIPE, handler);
  293.     
  294.     kill_timeout (r);
  295.     }
  296.     
  297.     pfclose (r->connection->pool, script_out);
  298.     
  299.     /* Handle script return... */
  300.     
  301.     if (script_in && !nph) {
  302.         char *location;
  303.     int ret;
  304.       
  305.         if ((ret = scan_script_header(r, script_in)))
  306.         return ret;
  307.     
  308.     location = table_get (r->headers_out, "Location");
  309.  
  310.         if (location && location[0] == '/' && r->status == 200) {
  311.       
  312.             /* Soak up all the script output */
  313.         hard_timeout ("read from script", r);
  314.         while (fgets(argsbuffer, HUGE_STRING_LEN-1, script_in) != NULL)
  315.             continue;
  316.         kill_timeout (r);
  317.         
  318.         internal_redirect (location, r);
  319.         return OK;
  320.         }
  321.     else if (location && r->status == 200) {
  322.         /* XX Note that if a script wants to produce its own Redirect
  323.          * body, it now has to explicitly *say* "Status: 302"
  324.          */
  325.         return REDIRECT;
  326.     }
  327.     
  328.     hard_timeout ("send script output", r);
  329.     send_http_header(r);
  330.         if(!r->header_only) send_fd (script_in, r);
  331.     kill_timeout (r);
  332.     pfclose (r->connection->pool, script_in);
  333.     }
  334.  
  335.     return OK;            /* NOT r->status, even if it has changed. */
  336. }
  337.  
  338. handler_rec cgi_handlers[] = {
  339. { CGI_MAGIC_TYPE, cgi_handler },
  340. { NULL }
  341. };
  342.  
  343. module cgi_module = {
  344.    STANDARD_MODULE_STUFF,
  345.    NULL,            /* initializer */
  346.    NULL,            /* dir config creater */
  347.    NULL,            /* dir merger --- default is to override */
  348.    NULL,            /* server config */
  349.    NULL,            /* merge server config */
  350.    NULL,            /* command table */
  351.    cgi_handlers,        /* handlers */
  352.    NULL,            /* filename translation */
  353.    NULL,            /* check_user_id */
  354.    NULL,            /* check auth */
  355.    NULL,            /* check access */
  356.    NULL,            /* type_checker */
  357.    NULL,            /* fixups */
  358.    NULL                /* logger */
  359. };
  360.